/**
 * @author harry
 * @date 2022/2/27/19:36
 */

package com.serviceOrchestration.pojo;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.serviceOrchestration.atomic.AtomicUnit;
import com.serviceOrchestration.atomic.AtomicUnitContext;
import lombok.Data;

@Data
public class Product {
    private volatile String id;
    private volatile String name;
    private volatile int period;
    private volatile int annualRate;
    private volatile int minAmount;
    private volatile int maxAmount;
    private volatile int incAmount;
    private volatile int dailyAmount;
    private volatile int surplus;
    private volatile boolean available;
    /**
     * 构造原子服务责任链的JSON串，便于存数据库。
     */
    private volatile String serviceJson;
    /**
     * 责任链的头节点
     */
    @JsonIgnore
    private volatile AtomicUnit services;
    @JsonIgnore
    private final Object lock = new Object();

    public boolean handle(AtomicUnitContext context) {
        int amount = (int) context.getContext("amount");
        int amountDaily = (int) context.getContext("amountDaily");
        int amountSum = (int) context.getContext("amountSum");
        String error = null;
        if(amount < minAmount || amount > maxAmount) {
            error = "不足或超出购买额度限制";
        }
        if((amount - minAmount) % incAmount != 0) {
            error = "购买数额增量不符合要求";
        }
        if(amount + amountDaily > dailyAmount) {
            error = "超出当日额度限制";
        }
        if(amount + amountSum > maxAmount) {
            error = "超出购买总额限制";
        }
        if(error != null) {
            context.setError(error);
            return false;
        }
        context.addContext("period", period);
        context.addContext("annualRate", annualRate);
        return services == null || services.handleRequest(context);
    }
}
